import json
from django.http import JsonResponse, HttpResponse
from django.views import View
from django.views.decorators.http import require_POST, require_GET

from utils.jwt_utils import create_jwt, jwt_required
from .models import User


@require_POST
def login(request):
    # 从请求体中获取JSON数据
    data = json.loads(request.body)
    # 从JSON数据中获取username和password
    username = data.get('username')
    password = data.get('password')

    # 验证用户名和密码是否存在于数据库中
    try:
        user = User.objects.get(username=username, password=password)
        token = create_jwt(username)
        return JsonResponse({"code": 0, "msg": "登录成功", "token": token})
    except User.DoesNotExist:
        return JsonResponse({"code": 401, "msg": "登录失败", "data": str(User.DoesNotExist)})


@require_POST
def register(request):
    data = json.loads(request.body)
    username = data.get('username')
    password = data.get('password')
    phone = data.get('phone')

    try:
        new_user = User.objects.create(username=username, password=password, phone=phone)
        return JsonResponse({"code": 0, "msg": "新增用户成功", "data": new_user.username})
    except Exception as e:
        return JsonResponse({"code": -1, "msg": "新增用户失败", "data": str(e)})


@require_GET
@jwt_required
def protected(request):
    return JsonResponse({"code": 0, "msg": "成功", "data": None})
